package com.wzm.hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.Test;

import com.lqm.hibernate.model.Comment;
import com.lqm.hibernate.model.News;

public class HibernateTest02 {
	@Test
	public void testList(){
		//注册服务
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
		.configure() // configures settings from hibernate.cfg.xml
		.build();
		//获取sessionFactory
		SessionFactory sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
		//获取session
		Session session = sessionFactory.openSession();
		//查询t_news表中的数据
		List<News> list = session.createQuery("from News").list();  //等价于select * from t_news
		System.out.println("总条数："+list.size());
		//关闭session
		session.close();
	}
	
	@Test
	public void testAdd(){
		// 注册服务
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
				.configure() // configures settings from hibernate.cfg.xml
				.build();
		// 获取sessionFactory
		SessionFactory sessionFactory = new MetadataSources(registry)
				.buildMetadata().buildSessionFactory();
		// 获取session
		Session session = sessionFactory.openSession();
		
		//*******************新增********************
		//实例化Comment
		Comment comt = new Comment(2,"张三峰","Hibernate So Easy~");
		//开启事务
		session.beginTransaction();
		session.save(comt);   //执行保存操作
		//提交事务
		session.getTransaction().commit();
		//*******************
		//关闭session
		session.close();
	}
	
	@Test
	public void testUpdate(){
		// 注册服务
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
				.configure() // configures settings from hibernate.cfg.xml
				.build();
		// 获取sessionFactory
		SessionFactory sessionFactory = new MetadataSources(registry)
				.buildMetadata().buildSessionFactory();
		// 获取session
		Session session = sessionFactory.openSession();
		
		//*******************修改********************
		Comment comt = new Comment(1,"张三","So Hard~");
		session.beginTransaction();
		session.update(comt);
		session.getTransaction().commit();
		//*******************
		//关闭session
		session.close();
	}
	
	@Test
	public void testDel(){
		// 注册服务
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
				.configure() // configures settings from hibernate.cfg.xml
				.build();
		// 获取sessionFactory
		SessionFactory sessionFactory = new MetadataSources(registry)
				.buildMetadata().buildSessionFactory();
		// 获取session
		Session session = sessionFactory.openSession();
		
		//*******************删除********************
		Comment comt = new Comment();
		comt.setId(1);
		session.beginTransaction();
		session.delete(comt);
		session.getTransaction().commit();
		//*******************
		//关闭session
		session.close();
	}
}
